package club.babyf.nativeai.functioncalling.functions;

import club.babyf.lbs.entity.amap.req.GeoCodeGeoParameterDto;
import club.babyf.lbs.entity.amap.req.WeatherInfoParameterDto;
import club.babyf.lbs.entity.amap.res.GeoCodeDto;
import club.babyf.lbs.entity.amap.res.GeoCodeGeoDto;
import club.babyf.lbs.entity.amap.res.WeatherInfoDto;
import club.babyf.lbs.entity.amap.res.WeatherLiveDto;
import club.babyf.lbs.service.LbsService;
import club.babyf.nativeai.functioncalling.annotation.RegisteredFunction;
import club.babyf.nativeai.functioncalling.entity.WeatherParams;
import club.babyf.nativeai.utils.JsonCustomUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * GetCurrentWeatherFunction.
 *
 * @author zhanglei.
 * @date 2025/2/21 10:51.
 * @description 获取当前天气函数.
 */
@Slf4j
@Component
@RegisteredFunction(name = "get_current_weather", description = "获取指定位置的当前天气")
public class GetCurrentWeatherFunction extends AbstractFunction<WeatherParams, String> {

    @Resource
    private LbsService lbsService;

    public GetCurrentWeatherFunction() {
        super(WeatherParams.class);
    }

    @Override
    protected String doExecute(WeatherParams params) {
        // 当前城市位置
        String location = params.getLocation();
        // 温度单位
        String unit = params.getUnit();
        log.info("获取天气信息，位置：{}，温度单位：{}", location, unit);
        // 获取城市编码
        GeoCodeGeoParameterDto geoCodeGeoParameterDto = new GeoCodeGeoParameterDto();
        geoCodeGeoParameterDto.setAddress(location);
        GeoCodeGeoDto geoCodeGeoDto = lbsService.geoCodeGeo(geoCodeGeoParameterDto);
        if (geoCodeGeoDto == null) {
            return "未获取到有效信息";
        }
        List<GeoCodeDto> geocodes = geoCodeGeoDto.getGeocodes();
        if (geocodes == null || geocodes.isEmpty()) {
            return "未获取到有效信息";
        }
        GeoCodeDto geoCodeDto = geocodes.get(0);
        String adcode = geoCodeDto.getAdcode();
        // 获取天气信息
        WeatherInfoParameterDto weatherInfoParameterDto = new WeatherInfoParameterDto();
        weatherInfoParameterDto.setCity(adcode);
        WeatherInfoDto weatherInfoDto = lbsService.weatherInfo(weatherInfoParameterDto);
        if (weatherInfoDto == null) {
            return "未获取到有效信息";
        }
        List<WeatherLiveDto> lives = weatherInfoDto.getLives();
        if (lives == null || lives.isEmpty()) {
            return "未获取到有效信息";
        }
        lives.forEach(weatherLiveDto -> log.info("天气信息：{}", weatherInfoDto));
        WeatherLiveDto weatherLiveDto = lives.get(0);
        // 返回天气信息
        return JsonCustomUtil.toJsonString(weatherLiveDto);
    }

}
